package com.tilaiedu.mvc.handler;

import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.NoHandlerFoundException;

import java.io.FileNotFoundException;

/**
 * @Author xlzhang
 * @Date 2022/5/30 10:00
 * @Version 1.0
 * @Description TODO
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    // 使用注解来指定当前方法要处理的具体异常
    @ExceptionHandler(ArithmeticException.class)
    public String handlerArithmeticException(Model model, ArithmeticException ex){
        System.out.println("handlerArithmeticException = " + ex.getMessage());
        model.addAttribute("errInfo",ex.getMessage());
        return "500";
    }

    @ExceptionHandler(NoHandlerFoundException.class)
    public String handlerNoHandlerFoundException(Model model, NoHandlerFoundException ex){
        System.out.println("handlerNoHandlerFoundException = " + ex.getMessage());
        model.addAttribute("errInfo",ex.getMessage());
        return "404";
    }

    // @ExceptionHandler(FileNotFoundException.class)
    // public String handlerArithmeticException(Model model, FileNotFoundException ex){
    //     System.out.println("ex = " + ex.getMessage());
    //     model.addAttribute("msg",ex.getMessage());
    //     return "500";
    // }

    @ExceptionHandler(Throwable.class)
    public String handlerException(Model model, Throwable ex){
        System.out.println("handlerException = " + ex.getMessage());
        model.addAttribute("errInfo",ex.getMessage());
        return "500";
    }

}
